﻿using System.Collections.ObjectModel;
using System.Collections.Specialized;
using MeterReader.PubSubEvents;
using MeterReader.WPF.Models;
using MeterReader.WPF.Services;

namespace MeterReader.WPF.ViewModels
{
    public class MetersDataMonitorViewModel : BindableBase
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly IReadData _dataService;
        private bool _isWorking = false;

        public MetersDataMonitorViewModel(IEventAggregator eventAggregator, IReadData dataService)
        {
            _eventAggregator = eventAggregator;
            _dataService = dataService;
            _dataService.WorkStatusChanged += WorkStatusChanged;
            MeterDataCollections = _dataService.GetMeterDataCollections();
            MeterDataCollections.CollectionChanged += MeterDataCollections_CollectionChanged;
            StartReadCommand = new DelegateCommand(StartRead, () => !IsWorking).ObservesProperty(() => IsWorking);
            StopReadCommand = new DelegateCommand(StopRead).ObservesCanExecute(() => IsWorking);
            GoHistoryCommand = new DelegateCommand<string>(Navigate);
            GoMetersCurveCommand = new DelegateCommand<string>(Navigate, (s) => MeterDataCollections.Any());
        }

        private void WorkStatusChanged(object? sender, EventArgs e)
        {
            IsWorking = _dataService.IsWorking;
            RaisePropertyChanged(nameof(IsWorking));
        }

        public ObservableCollection<MeterDataCollection> MeterDataCollections { get; set; } = new();
        public DelegateCommand StartReadCommand { get; set; }
        public DelegateCommand StopReadCommand { get; set; }
        public DelegateCommand<string> GoHistoryCommand { get; set; }
        public DelegateCommand<string> GoMetersCurveCommand { get; set; }
        public bool IsWorking
        {
            get { return _isWorking; }
            set { SetProperty(ref _isWorking, value); }
        }

        private void StopRead()
        {
            _dataService.StopRead();
        }

        private  void StartRead()
        {

            _dataService.StartRead();
        }

        private void MeterDataCollections_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) =>
            GoMetersCurveCommand.RaiseCanExecuteChanged();

        private void Navigate(string obj) => _eventAggregator.GetEvent<NavigateEvent>().Publish(obj);
    }
}
